<template>
  <div>
    <!-- 选择框用于选择菜品 -->
    <el-select 
      v-model="selectedDishes" 
      multiple 
      filterable 
      placeholder="选择菜品">
      <!-- 循环显示所有菜品选项 -->
      <el-option 
        v-for="dish in dishes" 
        :key="dish.id" 
        :label="dish.name" 
        :value="dish.id">
      </el-option>
    </el-select>
    <!-- 更新按钮 -->
    <el-button type="primary" @click="updateMeal">更新</el-button>
    <!-- 如果有已安排的菜品，显示它们 -->
    <div v-if="meal.length">
      <h4 style="text-align: left;">已安排的菜品</h4>
      <!-- 循环显示已安排的菜品 -->
      <div v-for="dish in meal" :key="dish.dish_id" class="dish-card">
        <el-card>
          <div style="display: flex; justify-content: space-between;">
            <div>{{ dish.name }}</div>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="removeDish(dish.dish_id)">
              <i class="el-icon-close"></i>
              删除
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import apiClient from '../api';
import { format } from 'date-fns'; // 导入 date-fns 用于格式化日期

export default {
  props: ['meal', 'selectedDate', 'activeMeal'],
  data() {
    return {
      dishes: [], // 存储所有菜品的数据
      selectedDishes: [] // 存储用户选择的菜品 ID
    };
  },
  watch: {
    meal: {
      handler: 'syncSelectedDishes',
      immediate: true // 确保在组件加载时立即调用该处理程序
    }
  },
  methods: {
    // 从后端加载所有菜品数据
    async loadDishes() {
      try {
        const response = await apiClient.get('/dishes');
        this.dishes = response.data;
        //console.log('Loaded dishes:', this.dishes); // 打印加载的菜品数据
        this.syncSelectedDishes(); // 加载完菜品数据后同步已选菜品
      } catch (error) {
        console.error('Error fetching dishes:', error);
      }
    },
    // 同步已选菜品，将已选菜品的 ID 存入 selectedDishes
    syncSelectedDishes() {
      // 打印调试信息
      //console.log('Syncing selected dishes with meal data:', this.meal);
      this.selectedDishes = this.meal.map(dish => {
        const foundDish = this.dishes.find(d => d.id === dish.dish_id);
        //console.log('Found dish:', foundDish); // 打印找到的菜品对象
        return foundDish ? foundDish.id : null;
      }).filter(dishId => dishId !== null); // 确保没有未定义的项
      //console.log('Selected dishes after sync:', this.selectedDishes); // 打印同步后的 selectedDishes
    },
    // 格式化日期为 'yyyy-MM-dd'
    formatDate(date) {
      return format(new Date(date), 'yyyy-MM-dd');
    },
    // 更新某天某餐的菜单
    async updateMeal() {
      try {
        const dish_ids = this.selectedDishes;
        //console.log('Updating meal with dish IDs:', dish_ids); // 调试输出
        // 将更新的菜品 ID 发送到后端
        await apiClient.post('/meal-plans', {
          date: this.formatDate(this.selectedDate), // 格式化日期
          meal: this.activeMeal,
          dish_ids
        });
        this.$emit('update'); // 触发父组件更新数据
      } catch (error) {
        console.error('Error updating meal:', error);
      }
    },
    // 从菜单中移除某个菜品
    async removeDish(dish_id) {
      try {
        await apiClient.delete('/meal-plans', {
          data: { date: this.formatDate(this.selectedDate), meal: this.activeMeal, dish_id } // 格式化日期
        });
        this.$emit('update'); // 触发父组件更新数据
      } catch (error) {
        console.error('Error removing meal:', error);
      }
    }
  },
  // 在组件挂载时加载菜品数据
  mounted() {
    this.loadDishes();
  }
};
</script>

<style scoped>
.dish-card {
  margin-bottom: 10px;
}
</style>